package com.lovegu.thread;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author 老顾
 * @title: AsyncProcessor
 * @projectName java-restudy
 * @email: 1437594522@qq.com
 * @date 2022/9/23 15:50
 */
public class AsyncProcessor {
    /**
     * 默认最大并发数<br>
     */
    private static final int DEFAULT_MAX_CONCURRENT = Runtime.getRuntime().availableProcessors() * 2;
    /**
     * 线程池名称格式
     */
    private static final String THREAD_POOL_NAME = "ydlclasslog-%d";
    /**
     * 线程工厂名称
     */
//    private static final ThreadFactory FACTORY = new BasicThreadFactory.Builder().namingPattern(THREAD_POOL_NAME)
//            .daemon(true).build();
    /**
     * 默认队列大小
     */
    private static final int DEFAULT_SIZE = 500;
    /**
     * 默认线程存活时间
     */
    private static final long DEFAULT_KEEP_ALIVE = 60L;
    /**
     * NewEntryServiceImpl.java:689
     * Executor
     */
    private static ExecutorService executor;
    /**
     * 执行队列
     */
    private static BlockingQueue<Runnable> executeQueue = new ArrayBlockingQueue<>(DEFAULT_SIZE);
    static {
        executor = new ThreadPoolExecutor(
                DEFAULT_MAX_CONCURRENT,
                DEFAULT_MAX_CONCURRENT * 4,
                DEFAULT_KEEP_ALIVE,
                TimeUnit.SECONDS,
                executeQueue);
    }
    /**
     * 此类型无法实例化
     */
    private AsyncProcessor() {
    }

    public static boolean executeTask(Runnable task)
    {
        try {
            executor.execute(task);
        } catch (RejectedExecutionException e) {
            System.out.println("Task executing was rejected.");
            return false;
        }
        return true;
    }
    /**
     * 提交任务，并可以在稍后获取其执行情况<br>
     * 当提交失败时，会抛出 {@link }
     * @param task
     * @return
     */
    public static <T> Future<T> submitTask(Callable<T> task) {
        try {
            return executor.submit(task);
        } catch (RejectedExecutionException e) {
            throw new UnsupportedOperationException("Unable to submit the task, rejected.", e);
        }
    }
}
